<?php

namespace App\Model;

use App\BaseModel;
use Illuminate\Support\Facades\DB;

class WineProductScene extends BaseModel
{
    protected $table = "wine_product_scene";

    protected $fillable = [
        'name',
        'icon',
        'creator',
        'updater',
        'user_id',
    ];

    protected $visible = ['id','name','icon','parent_id'];

    public function parent()
    {
        return $this->belongsTo('App\Model\WineProductScene','parent_id','id');
    }

    public function getParentNameAttribute()
    {
        return $this->parent?$this->parent->name:null;
    }

    public static function tree()
    {
        function tree($parent_id=0)
        {
            $items = [];

            $rows = DB::table('wine_product_scene')->where('parent_id','=',$parent_id)
                ->select('id','name','icon')->get();
            if (count($rows) > 0) {
                foreach ($rows as $index => $row) {
                    $d['name'] = $row->name;
                    $d['value'] = $row->id;
                    $d['icon'] = $row->icon;
                    $d['child'] = tree($row->id);
                    $items[] = $d;
                }
            }
            return $items;

        }

        return  tree();
    }
}
